package com.dw.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.article.mapper.mp.CommentUserMapper;
import com.dw.article.utils.LoginUtil;
import com.dw.model.article.dtos.comment.LikeCommentDTO;
import com.dw.model.article.entitys.CommentUser;
import com.dw.article.service.CommentUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 评论用户关系表(CommentUser)表服务实现类
 *
 * @author makejava
 * @since 2024-10-15 09:21:20
 */
@Service("commentUserService")
public class CommentUserServiceImpl extends ServiceImpl<CommentUserMapper, CommentUser> implements CommentUserService {

    @Resource
    private RedisTemplate redisTemplate;

    private final String COMMENT_LIKED_KEY = "comment.like";

    private final String COMMENT_LIKED_COUNT_KEY = "comment.like.count";

    private final String COMMENT_LIKED_DETAIL_KEY = "comment.like.detail";

    /**
     * 点赞
     */
    @Override
    public void like(LikeCommentDTO likeCommentDTO) {
        Long commentId = likeCommentDTO.getCommentId();
        long userId = Long.parseLong(LoginUtil.getLoginId());
        Integer isLiked = likeCommentDTO.getIsLiked();
        String hashKey = commentId + ":" + userId;
        redisTemplate.opsForHash().put(COMMENT_LIKED_KEY, hashKey, isLiked);
        String detailKey = COMMENT_LIKED_DETAIL_KEY + "." + commentId + "." + userId;
        String countKey = COMMENT_LIKED_COUNT_KEY + "." + commentId;
        if(isLiked == 1){
            redisTemplate.opsForValue().increment(countKey);
            redisTemplate.opsForValue().set(detailKey, 1);
        }else{
            Number result = (Number) redisTemplate.opsForValue().get(detailKey);
            if(result == null || result.longValue() <= 0){
                return;
            }
            redisTemplate.opsForValue().decrement(countKey);
            redisTemplate.delete(detailKey);
        }
    }

    /**
     * 查询当前评论点赞数
     */
    @Override
    public Integer getCommentLikeCount(Long commentId) {
        String likedKey = COMMENT_LIKED_COUNT_KEY + "." + commentId;
        Integer likedCount = (Integer) redisTemplate.opsForValue().get(likedKey);
        if(likedCount == null){
            likedCount = 0;
        }
        return likedCount;
    }

    /**
     * 查询当前用户是否点赞
     */
    @Override
    public Integer isLike(Long commentId) {
        long userId = Long.parseLong(LoginUtil.getLoginId());
        String hashKey = commentId + ":" + userId;
        Integer liked = (Integer) redisTemplate.opsForHash().get(COMMENT_LIKED_KEY, hashKey);
        if(liked != null && liked > 0){
            return 1;
        }
        return 0;
    }
}

